package logic

import (
	"context"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"order_srv/global"
	"order_srv/model"
	"order_srv/order_proto"
	"strconv"
)

// 获取用户购物车信息
func (s *Server) CartItemList(ctx context.Context, in *order_proto.UserInfo) (*order_proto.CartItemListResponse, error) {
	var shoppingCart []model.ShoppingCart
	tx := global.DB.Where(&model.ShoppingCart{UserId: int(in.UserId)}).Find(&shoppingCart)
	if tx.RowsAffected == 0 {
		return nil, status.Errorf(codes.Internal, "获取商品列表失败")
	}
	var shoppingCartList []*order_proto.ShopCartInfoResponse
	for _, v := range shoppingCart {
		shoppingCartList = append(shoppingCartList, &order_proto.ShopCartInfoResponse{
			Id:      v.ID,
			UserId:  int32(v.UserId),
			GoodsId: int32(v.GoodsId),
			Num:     v.Nums,
			Checked: v.Checked,
		})
	}
	return &order_proto.CartItemListResponse{
		ShopCartInfo: shoppingCartList,
		Total:        int32(tx.RowsAffected),
	}, nil
}

// 添加商品到购物车
func (s *Server) CreateCartItem(ctx context.Context, in *order_proto.CartItemRequest) (*order_proto.ShopCartInfoResponse, error) {
	var shoppingCart model.ShoppingCart
	first := global.DB.Where(&model.ShoppingCart{UserId: int(in.UserId), GoodsId: int(in.GoodsId)}).First(&shoppingCart)
	if first.RowsAffected == 0 {
		shoppingCart = model.ShoppingCart{
			UserId:  int(in.UserId),
			GoodsId: int(in.GoodsId),
			Nums:    in.Num,
			Checked: in.Checked,
		}
		tx := global.DB.Save(&shoppingCart)
		if tx.RowsAffected == 0 {
			return nil, status.Errorf(codes.Internal, "添加商品失败")
		}
	}
	shoppingCart.Nums += in.Num
	tx := global.DB.Save(&shoppingCart)
	if tx.Error != nil {
		return nil, status.Errorf(codes.Internal, "修改商品失败")
	}
	return &order_proto.ShopCartInfoResponse{
		Id:      shoppingCart.ID,
		UserId:  int32(shoppingCart.UserId),
		GoodsId: int32(shoppingCart.GoodsId),
		Num:     shoppingCart.Nums,
		Checked: shoppingCart.Checked,
	}, nil
}

// 修改购物车信息
func (s *Server) UpdateCartItem(ctx context.Context, in *order_proto.CartItemRequest) (*order_proto.Empty, error) {
	shoppingCart := model.ShoppingCart{}

	tx := global.DB.Model(&model.ShoppingCart{}).Where(model.ShoppingCart{
		BaseModel: model.BaseModel{
			ID: in.Id,
		},
	}).First(&shoppingCart)

	if tx.RowsAffected == 0 {
		return nil, status.Errorf(codes.Internal, "没有该购物车数据")
	}

	shoppingCart.Nums = in.Num
	shoppingCart.Checked = in.Checked
	save := global.DB.Model(&shoppingCart).Save(&shoppingCart)

	if save.Error != nil {
		return nil, status.Errorf(codes.Internal, "更新购物车失败")
	}

	return &order_proto.Empty{}, nil
}

// 删除购物车信息
func (s *Server) DeleteCartItem(ctx context.Context, in *order_proto.CartItemRequest) (*order_proto.Empty, error) {
	var shoppingCart model.ShoppingCart
	tx := global.DB.Where(&model.ShoppingCart{
		UserId:  int(in.UserId),
		GoodsId: int(in.GoodsId),
	}).First(&shoppingCart)
	if tx.RowsAffected == 0 {
		return nil, status.Errorf(codes.Internal, "购物车不存在")
	}
	db := global.DB.Delete(&shoppingCart)
	if db.Error != nil {
		return nil, status.Errorf(codes.Internal, "删除失败")
	}
	return &order_proto.Empty{}, nil
}

// 创建订单
//func (s *Server) Create(ctx context.Context, in *order_proto.OrderRequest) (*order_proto.OrderInfoResponse, error) {
//	var shoppingCart []model.ShoppingCart
//	goodsNumsMap := make(map[int32]int32)
//	//查询购物车商品是否存在
//	res := global.DB.Where(&model.ShoppingCart{UserId: int(in.UserId), Checked: true}).Find(&shoppingCart)
//	if res.RowsAffected == 0 {
//		return nil, status.Errorf(codes.Internal, "购物车不存在")
//	}
//	var goodsIDs []int32
//	for _, cart := range shoppingCart {
//		goodsIDs = append(goodsIDs, int32(cart.GoodsId))
//		goodsNumsMap[int32(cart.GoodsId)] = cart.Nums
//	}
//	//调用商品微服务
//	goods, err := global.GoodsSrvConnect.BatchGetGoods(context.Background(), &goods_proto.BatchGoodsIdInfo{Id: goodsIDs})
//	if err != nil {
//		return nil, status.Errorf(codes.Internal, "查询商品详情失败")
//	}
//	//订单总金额
//	var orderMount float32
//	// 商品库存详情
//	var goodsInvInfo []*inventory_proto.GoodsInvInfo
//	//订单商品
//	var orderGoods []*model.OrderGoods
//	for _, v := range goods.Data {
//		orderMount += v.ShopPrice * float32(goodsNumsMap[v.Id])
//		orderGoods = append(orderGoods, &model.OrderGoods{
//			GoodsId:    int(v.Id),
//			OrderId:    int(in.UserId),
//			GoodsName:  v.Name,
//			GoodsImage: v.GoodsFrontImage,
//			GoodsPrice: v.ShopPrice,
//			Nums:       int(goodsNumsMap[v.Id]),
//		})
//		goodsInvInfo = append(goodsInvInfo, &inventory_proto.GoodsInvInfo{
//			GoodsID: v.Id,
//			Nums:    goodsNumsMap[v.Id],
//		})
//	}
//	//调用库存微服务
//	_, err = global.InventorySrvConnect.Sell(context.Background(), &inventory_proto.SellInfo{
//		GoodsInfo: goodsInvInfo,
//	})
//	if err != nil {
//		return nil, status.Errorf(codes.Internal, "扣减库存失败")
//	}
//
//	tx := global.DB.Begin()
//	//生成唯一的订单编号
//	orderSn := fmt.Sprintf("%s", uuid.NewV4())
//	//创建订单基本信息表
//	orderInfo := model.OrderInfo{
//		UserId:       int(in.UserId),
//		OrderSn:      orderSn,
//		Status:       "PAYING",
//		OrderMount:   orderMount,
//		Address:      in.Address,
//		SingerName:   in.Name,
//		SingerMobile: in.Mobile,
//		Post:         in.Post,
//		PayTime:      time.Now(),
//	}
//	if result := tx.Create(&orderInfo); result.RowsAffected == 0 {
//		tx.Rollback()
//		return nil, status.Errorf(codes.Internal, "创建订单失败")
//	}
//	//循环赋值订单商品中的orderID
//	for k, _ := range orderGoods {
//		orderGoods[k].OrderId = int(orderInfo.ID)
//	}
//	//批量插入
//	if result := tx.CreateInBatches(orderGoods, 100); result.RowsAffected == 0 {
//		tx.Rollback()
//		return nil, status.Errorf(codes.Internal, "创建订单商品失败")
//	}
//	//从购物车中删除已购买的记录
//	if result := tx.Where(&model.ShoppingCart{UserId: int(in.UserId), Checked: true}).Delete(&shoppingCart); result.RowsAffected == 0 {
//		tx.Rollback()
//		return nil, status.Errorf(codes.Internal, "删除购物车商品失败")
//	}
//	tx.Commit()
//	return &order_proto.OrderInfoResponse{
//		Id:      orderInfo.ID,
//		UserId:  int32(orderInfo.UserId),
//		OrderSn: orderInfo.OrderSn,
//		PayType: strconv.Itoa(int(orderInfo.PayType)),
//		Status:  orderInfo.Status,
//		Post:    orderInfo.Post,
//		Total:   orderInfo.OrderMount,
//		Address: orderInfo.Address,
//		Name:    orderInfo.SingerName,
//		Mobile:  orderInfo.SingerMobile,
//	}, nil
//}

// 创建订单  Tcc
//func (s *Server) Create(ctx context.Context, in *order_proto.OrderRequest) (*order_proto.OrderInfoResponse, error) {
//	var shoppingCart []model.ShoppingCart
//	goodsNumsMap := make(map[int32]int32)
//	//查询购物车商品是否存在
//	res := global.DB.Where(&model.ShoppingCart{UserId: int(in.UserId), Checked: true}).Find(&shoppingCart)
//	if res.RowsAffected == 0 {
//		return nil, status.Errorf(codes.Internal, "购物车不存在")
//	}
//	var goodsIDs []int32
//	for _, cart := range shoppingCart {
//		goodsIDs = append(goodsIDs, int32(cart.GoodsId))
//		goodsNumsMap[int32(cart.GoodsId)] = cart.Nums
//	}
//	//调用商品微服务
//	goods, err := global.GoodsSrvConnect.BatchGetGoods(context.Background(), &goods_proto.BatchGoodsIdInfo{Id: goodsIDs})
//	if err != nil {
//		return nil, status.Errorf(codes.Internal, "查询商品详情失败")
//	}
//	//订单总金额
//	var orderMount float32
//	// 商品库存详情
//	var goodsInvInfo []*inventory_proto.GoodsInvInfo
//	//订单商品
//	var orderGoods []*model.OrderGoods
//	for _, v := range goods.Data {
//		orderMount += v.ShopPrice * float32(goodsNumsMap[v.Id])
//		orderGoods = append(orderGoods, &model.OrderGoods{
//			GoodsId:    int(v.Id),
//			OrderId:    int(in.UserId),
//			GoodsName:  v.Name,
//			GoodsImage: v.GoodsFrontImage,
//			GoodsPrice: v.ShopPrice,
//			Nums:       int(goodsNumsMap[v.Id]),
//		})
//		goodsInvInfo = append(goodsInvInfo, &inventory_proto.GoodsInvInfo{
//			GoodsID: v.Id,
//			Nums:    goodsNumsMap[v.Id],
//		})
//	}
//	//调用库存微服务  尝试扣减库存
//	_, err = global.InventorySrvConnect.TrySell(context.Background(), &inventory_proto.SellInfo{
//		GoodsInfo: goodsInvInfo,
//	})
//	if err != nil {
//		return nil, status.Errorf(codes.Internal, "扣减库存失败")
//	}
//
//	tx := global.DB.Begin()
//	//生成唯一的订单编号
//	orderSn := fmt.Sprintf("%s", uuid.NewV4())
//	//创建订单基本信息表
//	orderInfo := model.OrderInfo{
//		UserId:       int(in.UserId),
//		OrderSn:      orderSn,
//		Status:       "PAYING",
//		OrderMount:   orderMount,
//		Address:      in.Address,
//		SingerName:   in.Name,
//		SingerMobile: in.Mobile,
//		Post:         in.Post,
//		PayTime:      time.Now(),
//	}
//	if result := tx.Create(&orderInfo); result.RowsAffected == 0 {
//		tx.Rollback()
//		_, err = global.InventorySrvConnect.CancelSell(context.Background(), &inventory_proto.SellInfo{
//			GoodsInfo: goodsInvInfo,
//		})
//		if err != nil {
//			return nil, status.Errorf(codes.Internal, "取消扣减库存失败")
//		}
//		return nil, status.Errorf(codes.Internal, "创建订单失败")
//	}
//	//循环赋值订单商品中的orderID
//	for k, _ := range orderGoods {
//		orderGoods[k].OrderId = int(orderInfo.ID)
//	}
//	//批量插入
//	if result := tx.CreateInBatches(orderGoods, 100); result.RowsAffected == 0 {
//		tx.Rollback()
//		_, err = global.InventorySrvConnect.CancelSell(context.Background(), &inventory_proto.SellInfo{
//			GoodsInfo: goodsInvInfo,
//		})
//		if err != nil {
//			return nil, status.Errorf(codes.Internal, "取消扣减库存失败")
//		}
//		return nil, status.Errorf(codes.Internal, "创建订单商品失败")
//	}
//	//从购物车中删除已购买的记录
//	if result := tx.Where(&model.ShoppingCart{UserId: int(in.UserId), Checked: true}).Delete(&shoppingCart); result.RowsAffected == 0 {
//		tx.Rollback()
//		_, err = global.InventorySrvConnect.CancelSell(context.Background(), &inventory_proto.SellInfo{
//			GoodsInfo: goodsInvInfo,
//		})
//		if err != nil {
//			return nil, status.Errorf(codes.Internal, "取消扣减库存失败")
//		}
//		return nil, status.Errorf(codes.Internal, "删除购物车商品失败")
//	}
//	tx.Commit()
//	//扣减真实库存
//	_, err = global.InventorySrvConnect.ConfirmSell(context.Background(), &inventory_proto.SellInfo{
//		GoodsInfo: goodsInvInfo,
//	})
//	if err != nil {
//		return nil, status.Errorf(codes.Internal, "确认扣减库存失败")
//	}
//	return &order_proto.OrderInfoResponse{
//		Id:      orderInfo.ID,
//		UserId:  int32(orderInfo.UserId),
//		OrderSn: orderInfo.OrderSn,
//		PayType: strconv.Itoa(int(orderInfo.PayType)),
//		Status:  orderInfo.Status,
//		Post:    orderInfo.Post,
//		Total:   orderInfo.OrderMount,
//		Address: orderInfo.Address,
//		Name:    orderInfo.SingerName,
//		Mobile:  orderInfo.SingerMobile,
//	}, nil
//}

// 订单列表
func (s *Server) OrderList(ctx context.Context, in *order_proto.OrderFilterRequest) (*order_proto.OrderListResponse, error) {
	var orderInfo []model.OrderInfo
	localDB := global.DB.Model(&model.OrderInfo{})
	//筛选userId
	if in.UserId > 0 {
		localDB.Where("user_id = ?", in.UserId)
	}
	//筛选支付方式
	if in.PayType >= 0 {
		localDB.Where("pay_type = ?", in.PayType)
	}
	//筛选支付状态
	if len(in.Status) != 0 {
		localDB.Where("status = ?", in.Status)
	}
	//分页查询订单详情列表
	tx := localDB.Scopes(Paginate(int(in.Page), int(in.Limit))).Find(&orderInfo)
	if tx.Error != nil {
		return nil, status.Errorf(codes.Internal, "查询订单失败")
	}
	var orderList []*order_proto.OrderInfoResponse
	for _, info := range orderInfo {
		orderList = append(orderList, &order_proto.OrderInfoResponse{
			Id:      info.ID,
			UserId:  int32(info.UserId),
			OrderSn: info.OrderSn,
			PayType: strconv.Itoa(int(info.PayType)),
			Status:  info.Status,
			Post:    info.Post,
			Total:   info.OrderMount,
			Address: info.Address,
			Name:    info.SingerName,
			Mobile:  info.SingerMobile,
		})
	}
	return &order_proto.OrderListResponse{
		OrderInfo: orderList,
		Total:     int32(tx.RowsAffected),
	}, nil
}

// 订单详情
func (s *Server) OrderDetail(ctx context.Context, in *order_proto.OrderRequest) (*order_proto.OrderInfoDetailResponse, error) {
	var orderInfo model.OrderInfo
	//查询订单详情信息
	global.DB.Where(&model.OrderInfo{OrderSn: in.OrderSn}).Find(&orderInfo)
	var orderInfos *order_proto.OrderInfoResponse
	orderInfos = &order_proto.OrderInfoResponse{
		Id:      orderInfo.ID,
		UserId:  int32(orderInfo.UserId),
		OrderSn: orderInfo.OrderSn,
		PayType: strconv.Itoa(int(orderInfo.PayType)),
		Status:  orderInfo.Status,
		Post:    orderInfo.Post,
		Total:   orderInfo.OrderMount,
		Address: orderInfo.Address,
		Name:    orderInfo.SingerName,
		Mobile:  orderInfo.SingerMobile,
	}
	var orderGoods []model.OrderGoods
	//查询订单商品信息
	global.DB.Where(&model.OrderGoods{OrderId: int(in.ID)}).Find(&orderGoods)
	var ordergoods []*order_proto.OrderItemResponse
	for _, v := range orderGoods {
		ordergoods = append(ordergoods, &order_proto.OrderItemResponse{
			Id:         v.ID,
			OrderId:    int32(v.OrderId),
			GoodsId:    int32(v.GoodsId),
			GoodsName:  v.GoodsName,
			GoodsImage: v.GoodsImage,
			GoodsPrice: v.GoodsPrice,
			Nums:       int32(v.Nums),
		})
	}
	return &order_proto.OrderInfoDetailResponse{
		OrderInfo: orderInfos,
		Goods:     ordergoods,
	}, nil
}

// 修改订单状态
func (s *Server) UpdateOrder(ctx context.Context, in *order_proto.UpdateOrderInfo) (*order_proto.Empty, error) {
	var orderInfo model.OrderInfo
	tx := global.DB.Where(&model.OrderInfo{OrderSn: in.OrderSn}).First(&orderInfo)
	if tx.RowsAffected == 0 {
		return nil, status.Errorf(codes.Internal, "订单不存在")
	}
	orderInfo.Status = in.Status
	payType, _ := strconv.Atoi(in.PayType)
	orderInfo.PayType = int8(payType)
	orderInfo.TradeNo = in.TradeNo
	save := global.DB.Save(&orderInfo)
	if save.Error != nil {
		return nil, status.Errorf(codes.Internal, "修改失败")
	}
	return &order_proto.Empty{}, nil
}
